<template>
  <!-- 滑动列表容器 -->
  <div class="swipe-list-container" ref="container" :style="{ width: width }">
    <!-- 滑动内容区域 -->
    <div
      class="swipe-list-wrapper"
      ref="wrapper"
      :style="wrapperStyle"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      @mousedown="handleMouseDown"
      @mousemove="handleMouseMove"
      @mouseup="handleMouseUp"
      @mouseleave="handleMouseLeave"
    >
      <!-- 插槽：用于插入列表项 -->
      <slot></slot>
    </div>

    <!-- 左右滑动提示箭头（仅在可滑动时显示） -->
    <div
      class="swipe-arrow left-arrow"
      @click="scrollBy(-scrollStep)"
      v-if="canScrollLeft"
    >
      <svg
        width="24"
        height="24"
        viewBox="0 0 24 24"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path
          d="M15 19L8 12L15 5"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
        />
      </svg>
    </div>
    <div
      class="swipe-arrow right-arrow"
      @click="scrollBy(scrollStep)"
      v-if="canScrollRight"
    >
      <svg
        width="24"
        height="24"
        viewBox="0 0 24 24"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path
          d="M9 5L16 12L9 19"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
        />
      </svg>
    </div>
  </div>
</template>

<script>
export default {
  name: "SwipeList",
  props: {
    width: {
      type: String,
      default: "100%",
    },
    // 每次点击箭头滑动的距离
    scrollStep: {
      type: Number,
      default: 200,
    },
    // 列表项之间的间距（px）
    itemSpacing: {
      type: Number,
      default: 16,
    },
    // 是否显示滑动箭头
    showArrows: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      // 滑动相关变量
      startX: 0, // 触摸/鼠标按下的X坐标
      currentScrollLeft: 0, // 当前滚动位置
      isDragging: false, // 是否正在拖动
      initialScrollLeft: 0, // 开始拖动时的滚动位置

      // 容器尺寸
      containerWidth: 0, // 容器宽度
      contentWidth: 0, // 内容总宽度
    };
  },
  computed: {
    // 滑动容器样式
    wrapperStyle() {
      return {
        padding: `0 ${this.showArrows ? "40px" : "0"}`, // 为箭头预留空间
        gap: `${this.itemSpacing}px`,
      };
    },
    // 是否可以向左滚动（内容有向左滚动的空间）
    canScrollLeft() {
      return this.currentScrollLeft > 10; // 留一点误差
    },
    // 是否可以向右滚动（内容有向右滚动的空间）
    canScrollRight() {
      return (
        this.currentScrollLeft < this.contentWidth - this.containerWidth - 10
      ); // 留一点误差
    },
  },
  mounted() {
    // 初始化
    this.$nextTick(() => {
      this.updateDimensions();

      // 监听窗口大小变化
      window.addEventListener("resize", this.handleResize);

      // 监听内容变化（适用于动态加载的列表）
      const observer = new MutationObserver(this.updateDimensions);
      observer.observe(this.$refs.wrapper, {
        childList: true,
        subtree: true,
        attributes: true,
      });

      this.$once("hook:beforeDestroy", () => {
        observer.disconnect();
      });
    });
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
  },
  methods: {
    // 更新容器和内容尺寸
    updateDimensions() {
      if (!this.$refs.container || !this.$refs.wrapper) return;

      this.containerWidth = this.$refs.container.offsetWidth;
      this.contentWidth = this.$refs.wrapper.scrollWidth;
      this.currentScrollLeft = this.$refs.wrapper.scrollLeft;
    },

    // 处理窗口大小变化
    handleResize() {
      this.$nextTick(this.updateDimensions);
    },

    // 触摸开始
    handleTouchStart(e) {
      this.startX = e.touches[0].clientX;
      this.initialScrollLeft = this.$refs.wrapper.scrollLeft;
      this.isDragging = true;

      // 清除可能的动画
      this.$refs.wrapper.style.scrollBehavior = "auto";
    },

    // 触摸移动
    handleTouchMove(e) {
      if (!this.isDragging) return;

      const currentX = e.touches[0].clientX;
      const diffX = currentX - this.startX;

      // 应用滚动
      this.$refs.wrapper.scrollLeft = this.initialScrollLeft - diffX;
      this.currentScrollLeft = this.$refs.wrapper.scrollLeft;

      // 阻止页面垂直滚动
      e.preventDefault();
    },

    // 触摸结束
    handleTouchEnd() {
      if (!this.isDragging) return;

      this.isDragging = false;
      // 恢复平滑滚动
      this.$refs.wrapper.style.scrollBehavior = "";
    },

    // 鼠标按下（桌面端）
    handleMouseDown(e) {
      this.startX = e.clientX;
      this.initialScrollLeft = this.$refs.wrapper.scrollLeft;
      this.isDragging = true;

      // 添加拖动样式
      this.$refs.wrapper.style.cursor = "grabbing";
      document.body.style.userSelect = "none";

      // 清除可能的动画
      this.$refs.wrapper.style.scrollBehavior = "auto";
    },

    // 鼠标移动（桌面端）
    handleMouseMove(e) {
      if (!this.isDragging) return;

      const currentX = e.clientX;
      const diffX = currentX - this.startX;

      // 应用滚动
      this.$refs.wrapper.scrollLeft = this.initialScrollLeft - diffX;
      this.currentScrollLeft = this.$refs.wrapper.scrollLeft;
    },

    // 鼠标释放（桌面端）
    handleMouseUp() {
      if (!this.isDragging) return;

      this.isDragging = false;
      this.$refs.wrapper.style.cursor = "grab";
      document.body.style.userSelect = "";
      // 恢复平滑滚动
      this.$refs.wrapper.style.scrollBehavior = "";
    },

    // 鼠标离开容器（桌面端）
    handleMouseLeave() {
      if (this.isDragging) {
        this.handleMouseUp();
      }
    },

    // 按指定距离滚动
    scrollBy(distance) {
      if (!this.$refs.wrapper) return;

      const newScrollLeft = this.$refs.wrapper.scrollLeft + distance;
      this.$refs.wrapper.scrollTo({
        left: newScrollLeft,
        behavior: "smooth",
      });
    },
  },
  watch: {
    // 监听滚动位置变化
    currentScrollLeft(newVal) {
      this.$emit("scroll", newVal);
    },
  },
};
</script>

<style scoped>
.swipe-list-container {
  position: relative;
  overflow: hidden;
  touch-action: pan-y; /* 优化触摸体验，允许垂直滚动但优化水平滑动 */
}

.swipe-list-wrapper {
  height: 210px;
  display: flex;
  overflow-x: auto;
  overflow-y: hidden;
  scrollbar-width: none; /* 隐藏Firefox滚动条 */
  -ms-overflow-style: none; /* 隐藏IE和Edge滚动条 */
  cursor: grab;
  will-change: scroll-position;
}

/* 隐藏Chrome等webkit浏览器滚动条 */
.swipe-list-wrapper::-webkit-scrollbar {
  display: none;
}

.swipe-list-wrapper:active {
  cursor: grabbing;
}

/* 箭头样式 */
.swipe-arrow {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10;
  color: #666;
  transition: all 0.2s ease;
  user-select: none;
}

.swipe-arrow:hover {
  background-color: #fff;
  color: #333;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.left-arrow {
  left: 0;
}

.right-arrow {
  right: 0;
}

/* 插槽中的列表项默认样式（可被覆盖） */
.swipe-list-wrapper > * {
  flex-shrink: 0; /* 防止项目被压缩 */
}
</style>
